/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.ucue.ptc.gco.util;

import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Marcelo
 */
public class CedulaUtil {
    
    static final int DIGCED = 10;

    public static String generaCedula() {
        Random r = new Random();
        String cedula = r.nextInt(5) + "";//primer digito
        for (int c = 1; c < DIGCED - 1; c++) {
            cedula += (c == 2 ? r.nextInt(6) : r.nextInt(DIGCED)) + "";
        }
        try {
            cedula += ultimoDigitoCedula(cedula);
        } catch (Exception ex) {
            System.err.println("Error generando cedula: " + cedula + " - " + ex.getMessage());
            return null;
        }

        return cedula;
    }

    public static boolean isValidCedula(String cedula) //Devuelve true si la cedula ingresada en un vector de ints es verdadera, caso contrario false
    {
        try {
            if (cedula == null || Integer.parseInt(cedula.charAt(2) + "") >= 6 || cedula.length() != DIGCED) {
                return false;
            }
            return Integer.parseInt(cedula.charAt(DIGCED - 1) + "") == ultimoDigitoCedula(cedula);
        } catch (Exception ex) {
            System.err.println("Error validando cedula: " + cedula + " - " + ex.getMessage());
            return false;
        }
    }

    public static int ultimoDigitoCedula(String cedula) throws Exception {
        int f = 0;
        for (int i = 0, t; i < DIGCED - 1; i++, f += (t >= 10 ? t - 9 : t)) {
            t = Integer.parseInt(cedula.charAt(i) + "") * (i % 2 == 0 ? 2 : 1);
        }//usando condicionales
        return (10 - f % 10) % 10;
        /*
         for (int i = 0; i < n.length - 1; i++) {
             f += n[i] * (2 - i % 2) - n[i]/5*9;
         }//usando solo operaciones matematicas
         */        
    }
}
